{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reverse a Linked List\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/lvEC4JlPSGUDw9t7I3jSdg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value, next_node=None):\n",
    "        self.value = value\n",
    "        self.next_node = next_node\n",
    "\n",
    "    def __str__(self) -> str:\n",
    "        pointer = self\n",
    "        nodes = list()\n",
    "        while pointer is not None:\n",
    "            nodes.append(pointer.value)\n",
    "            pointer = pointer.next_node\n",
    "        return ' -> '.join(nodes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def iteratively_reverse(linked_list: Node) -> Node:\n",
    "    pointer_A = linked_list\n",
    "    pointer_B = None\n",
    "    while pointer_A is not None:\n",
    "        pointer_B = Node(pointer_A.value, pointer_B)\n",
    "        pointer_A = pointer_A.next_node\n",
    "    return pointer_B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def recursively_reverse(linked_list: Node) -> str:\n",
    "    if linked_list.next_node is None:\n",
    "        return linked_list.value\n",
    "    else:\n",
    "        return Node(\n",
    "            recursively_reverse(linked_list.next_node),\n",
    "            Node(linked_list.value)\n",
    "        ).__str__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 -> 1 -> 2 -> 3 -> 4\n",
      "0 -> 1 -> 2 -> 3 -> 4\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    iteratively_reverse(\n",
    "        Node('4', Node('3', Node('2', Node('1', Node('0')))))\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    recursively_reverse(\n",
    "        Node('4', Node('3', Node('2', Node('1', Node('0')))))\n",
    "    )\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
